// import {DatePicker} from 'react-datepicker';
var Content = React.createClass({
    render:function(){
        return(
            <Calendar />
        )
    }
});
let Data =[
        {
          rangeYear:"2017",
          rangeMonth:"3",
          rangeDay:"13",         
          eventLists:[
            {
              rangeTime:"13:00-14:00",
              eventDes:"乐视屏幕播放...",
              className:"addClicked",
            },
            {
              rangeTime:"13:00-14:00",
              eventDes:"小米屏幕播放...",
              className:"addClicked",
            },
            {
              rangeTime:"13:00-14:00",
              eventDes:"中央屏幕...",
              className:"addClicked",
            },
            {
              rangeTime:"13:00-14:00",
              eventDes:"电梯广告屏幕...",
              className:"addClicked",
            }
          ]
        },
        {
          rangeYear:"2017",
          rangeMonth:"3",
          rangeDay:"14",
          eventLists:[
            {
              rangeTime:"13:00-14:00",
              eventDes:"广场屏幕...",
              className:"addClicked",
            }
          ]
        }
]
//获取一年中每个月的显示数据,每个数据为6行*7天
const displayDaysPerMonth = (year)=> {

  //定义每个月的天数，如果是闰年第二月改为29天
  let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
    daysInMonth[1] = 29
  }

  //以下为了获取一年中每一个月在日历选择器上显示的数据，
  //从上个月开始，接着是当月，最后是下个月开头的几天

  //定义一个数组，保存上一个月的天数
  let daysInPreviousMonth = [].concat(daysInMonth)
  daysInPreviousMonth.unshift(daysInPreviousMonth.pop())

  //获取每一个月显示数据中需要补足上个月的天数
  let addDaysFromPreMonth = new Array(12)
    .fill(null)
    .map((item, index)=> {
      let day = new Date(year, index, 1).getDay()
      if (day === 0) {
        return 6
      } else {
        return day - 1
      }
    })

  //以数组形式返回一年中每个月的显示数据,每个数据为6行*7天
  return new Array(12)
    .fill([])
    .map((month, monthIndex)=> {
      let addDays = addDaysFromPreMonth[monthIndex],
        daysCount = daysInMonth[monthIndex],
        daysCountPrevious = daysInPreviousMonth[monthIndex],
        monthData = []
      //补足上一个月
      for (; addDays > 0; addDays--) {
        monthData.unshift(daysCountPrevious--)
      }
      //添入当前月
      for (let i = 0; i < daysCount;) {
        monthData.push(++i)
      }
      //补足下一个月
      for (let i = 42 - monthData.length, j = 0; j < i;) {
        monthData.push(++j)
      }
      return monthData
    })
}
//整体组件，整合CalendarHeader,CalendarMonthView,CalendarWeekView
class Calendar extends React.Component {
  constructor() {
    //继承React.Component
    super()
    let now = new Date()
    //初始化状态
    this.state = {
      year: now.getFullYear(),
      month: now.getMonth(),
      day: now.getDate(),
      weekDay:now.getDay(),
      picked: false,
      isMonthView:true,
      isShowAddEventComponent:false,
      data:[]
    }
  }
  //添加事件
  addEvent(){

  }
  //切换到今天
  today(){
    let now = new Date();
    this.setState({
      year: now.getFullYear(),
      month: now.getMonth(),
      day: now.getDate(),
      picked:true
    }) 
  }
  //周视图
  weekView(){
    this.setState({
      isMonthView:false
    })
  }
  //月视图
  monthView(){
    this.setState({
      isMonthView:true
    })
  }
  //切换到下一个月
  nextMonth() {
    //如果当前是十二月，切换到下一年一月份
    if (this.state.month === 11) {
      this.setState({
        year: ++this.state.year,
        month: 0,
        day:1
      })
    } else {
      this.setState({
        month: ++this.state.month,
        day:1
      })
    }
  }
  //切换到上一个月
  prevMonth() {
    if (this.state.month === 0) {
      this.setState({
        year: --this.state.year,
        month: 11,
        day:1
      })
    } else {
      this.setState({
        month: --this.state.month,
        day:1
      })
    }
  }
  //切换到上一周
  prevWeek(){
    //定义每个月的天数，如果是闰年第二月改为29天
    let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if ((this.state.year % 4 === 0 && this.state.year % 100 !== 0) || this.state.year % 400 === 0) {
      daysInMonth[1] = 29
    }
    //如果当前日期减去一周小于1，说明要切还到上个月最后一周
    if(this.state.day-7<1){
      this.prevMonth();
      this.setState({
        day:daysInMonth[this.state.month]
      })
    }else{
      this.setState({
        day:this.state.day-7
      })
    }   
  }
  //切换到下一周
  nextWeek(){
    //定义每个月的天数，如果是闰年第二月改为29天
    let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if ((this.state.year % 4 === 0 && this.state.year % 100 !== 0) || this.state.year % 400 === 0) {
      daysInMonth[1] = 29
    }
    console.log("wo shi day+7:"+ (this.state.day + 7));
    //如果当前日期加一周大于当前月份最大天数，说明要切换到下个月第一周
    if(this.state.day+7>daysInMonth[this.state.month]){
      this.nextMonth();
    }else{
      this.setState({
        day:this.state.day+7
      })
    }
  }
  //判断是执行上一周还是执行上一周方法
  prev(){
    if(this.state.isMonthView){
      this.prevMonth();
    }else{
      this.prevWeek();
    }
  }
  //判断是执行下一周还是执行下一月方法
  next(){
    if(this.state.isMonthView){
      this.nextMonth();
    }else{
      this.nextWeek();
    }
  }
  //选择日期
  datePick(day) {
    this.setState({day})
  }
  //标记日期已经选择
  picked() {
    this.state.picked = true
  }
  //添加事件后更新数据
  updateData(curData){
    this.setState({
      data:curData
    });
  }
  //显示增加事件页面
  showAddEvent(){
    console.log("我是showAddEvent"+this.state.isShowAddEventComponent)
    this.setState({
      isShowAddEventComponent:true
    })
  }
  //关闭增加事件页面
  closeAddEvent(){
    this.setState({
      isShowAddEventComponent:false
    })
  }
  render() {
    let props = {
      //获取这一年每个月要显示的数据
      viewData: displayDaysPerMonth(this.state.year),
      //获取当前选择的日期
      datePicked: `${this.state.year} 年 ${this.state.month + 1} 月 ${this.state.day} 日`
    }
    return (
          <div className="output">
            <CalendarHeader showAddEvent={this.showAddEvent.bind(this)}
                            prevMonth={this.prevMonth.bind(this)}
                            nextMonth={this.nextMonth.bind(this)}
                            prev={this.prev.bind(this)}
                            next={this.next.bind(this)}
                            weekView={this.weekView.bind(this)}
                            monthView={this.monthView.bind(this)}
                            isMonthView={this.state.isMonthView}
                            today={this.today.bind(this)}
                            year={this.state.year}
                            month={this.state.month}
                            day={this.state.day}
                            datePick={props.datePicked}/>
            <div className="main" ref="main">

              {this.state.isMonthView?
                <CalendarMonthView {...props}
                    prevMonth={this.prevMonth.bind(this)}
                    nextMonth={this.nextMonth.bind(this)}
                    prev={this.prev.bind(this)}
                    next={this.next.bind(this)}
                    datePick={this.datePick.bind(this)}
                    showAddEvent={this.showAddEvent.bind(this)}
                    year={this.state.year}
                    month={this.state.month}
                    day={this.state.day}
                    data={this.state.data}/>:<CalendarWeekView {...props}
                                                prevMonth={this.prevMonth.bind(this)}
                                                nextMonth={this.nextMonth.bind(this)}
                                                prev={this.prev.bind(this)}
                                                next={this.next.bind(this)}                           
                                                datePick={this.datePick.bind(this)}
                                                showAddEvent={this.showAddEvent.bind(this)}
                                                year={this.state.year}
                                                month={this.state.month}
                                                day={this.state.day}
                                                data={this.state.data}/>}
              
            </div>
            {this.state.isShowAddEventComponent?
              <AddEventDialogue 
                  year={this.state.year}
                  month={this.state.month}
                  day={this.state.day}
                  data={this.state.data}
                  datePicked={props.datePicked}
                  closeAddEvent={this.closeAddEvent.bind(this)}
                  updateData={this.updateData.bind(this)}
                  cancle={this.closeAddEvent.bind(this)} />:''}  
          </div>
    )
  }
}

//日历头部组件
class CalendarHeader extends React.Component {
  render() {
    let curDate=new Date();
    curDate = curDate.getDate();
    return (
      <div className="calendarHeader">
        <span className="addEvent" onClick={this.props.showAddEvent}>+</span>
        <span className={this.props.day==curDate?"todayClicked":"today"} onClick={this.props.today}>今天</span>
        <span className="prev fc-icon fc-icon-left-single-arrow" onClick={this.props.prev}></span>
        <span className="dateInfo">{this.props.datePick}</span>
        <span className="next fc-icon fc-icon-right-single-arrow" onClick={this.props.next}></span> 
        <a className="weekView fa fa-times" href="/console"></a> 
        <span className={this.props.isMonthView?"weekView":"weekViewClicked"} onClick={this.props.weekView}>周</span> 
        <span className={this.props.isMonthView?"monthViewClicked":"monthView"} onClick={this.props.monthView}>月</span>      
        <table className="tableHeader">
          <thead>
            <tr>
              <th>星期一</th>
              <th>星期二</th>
              <th>星期三</th>
              <th>星期四</th>
              <th>星期五</th>
              <th>星期六</th>
              <th>星期日</th>
            </tr>
          </thead>
        </table>
      </div>
      
    )
  }
}

//月视图组件
class CalendarMonthView extends React.Component {
  //处理事件数据，根据日期返回当天的事件列表
  handleEventSelect(year,month,day,style,data){
    //处理月份和年份
    if(style=="thisMonth"){
      month=month;
    }else if(style=="prevMonth"){
      if(month==0){
        month=11;
        year=year-1;
      }else{
        month=month-1;
      }
    }else if(style=="nextMonth"){
      if(month==11){
        month=0;
        year=year+1;
      }else{
        month=month+1;
      }
    }
    // 查找符合条件的数据
    let curEvent;
    data.forEach(function(event,index){
      if(event.rangeYear==year&&event.rangeMonth==month&&event.rangeDay==day){
        curEvent = event;
        return;
      }
    })
    //找到返回curEvent，找不到返回false
    return curEvent?curEvent:false;
  }
  //处理日期选择事件，如果是当月，触发日期选择；如果不是当月，切换月份
  handleDatePick(index, styleName,e) {
    e=e||window.event;
    let month = this.props.viewData[this.props.month]
    switch (styleName) {
      case 'thisMonth':
        break
      case 'prevMonth':
        this.props.prevMonth() 
        break
      case 'nextMonth':        
        this.props.nextMonth()
        break
    }
    this.props.datePick(month[index])
  }

  //处理选择时选中的样式效果
  //利用闭包保存上一次选择的元素，
  //在月份切换和重新选择日期时重置上一次选择的元素的样式
  changeColor() {
    let previousEl = null
    return function (event) {
      let name = event.target.nodeName.toLocaleLowerCase()
      if (previousEl && (name === 'i' || name === 'td')) {
        previousEl.style = ''
      }
      if (event.target.className === 'thisMonth') {
        event.target.style = 'background:#F8F8F8;color:#000'
        previousEl = event.target
      }
    }
  }

  //绑定颜色改变事件,componentDidMount类似js中的window.onload，执行在render方法之后，也就是页面的组件渲染完毕之后
  componentDidMount() {
    let changeColor = this.changeColor()
    document.getElementById('wrapper')
      .addEventListener('click', changeColor, false);

  }
  render() {
    //确定当前月数据中每一天所属的月份，以此赋予不同className
    let month = this.props.viewData[this.props.month],
      rowsInMonth = [],
      i = 0,
      styleOfDays = (()=> {
        let i = month.indexOf(1),
          j = month.indexOf(1, i + 1),
          arr = new Array(42)
        arr.fill('prevMonth', 0, i)
        arr.fill('thisMonth', i, j)
        arr.fill('nextMonth', j)
        return arr
      })()

    //把每一个月的显示数据以7天为一组等分
    month.forEach((day, index)=> {
      if (index % 7 === 0) {
        rowsInMonth.push(month.slice(index, index + 7))
      }
    })
    let _this=this;
    return (
      <table className="calendarMain">
        <tbody>
        {
          rowsInMonth.map((row, rowIndex)=> {
            return (
              <tr key={rowIndex}>
                {
                  row.map((day)=> {
                    let curEvent=this.handleEventSelect(this.props.year, this.props.month, day, styleOfDays[i],Data);
                    curEvent = curEvent.eventLists;
                    {/*let strLists="";*/}
                    return (
                      <td className={styleOfDays[i]}
                          onClick={
                            this.handleDatePick.bind
                            (this, i, styleOfDays[i])}
                          key={i++}>
                        <div className={(day==this.props.day&&styleOfDays[i-1]=="thisMonth")?"preDayClicked":"preDay"}>
                          <b>{day}</b>{curEvent?("--"+curEvent.length+"张卡片"):""}
                          {
                            curEvent&&curEvent.map(function(item,index){
                              {/*strLists+="<div className='addClicked' >"+item.eventDes+"</div>";
                              console.log(strLists)
                              if(index<2){*/}
                                return <div key={"curEvent"+index} className="addClicked" >{item.eventDes}</div>
                              {/*}else if(index==2){
                                return <div className="addClicked">...</div>
                              }else{
                                return;
                              }*/}
                              
                            })
                          }
                          <div className={(day==this.props.day&&styleOfDays[i-1]=="thisMonth")?"addClicked":"addUnClick"} onClick={this.props.showAddEvent}>添加屏幕播放内容...</div>
                        </div>
                      </td>
                    )
                  })
                }
              </tr>
            )
          })
        }
        </tbody>
      </table>
    )
  }
}

//周视图组件
class CalendarWeekView extends React.Component {
  //处理事件数据，根据日期返回当天的事件列表
  handleEventSelect(year,month,day,style,data){
    //处理月份和年份
    if(style=="thisMonth"){
      month=month;
    }else if(style=="prevMonth"){
      if(month==0){
        month=11;
        year=year-1;
      }else{
        month=month-1;
      }
    }else if(style=="nextMonth"){
      if(month==11){
        month=0;
        year=year+1;
      }else{
        month=month+1;
      }
    }
    // 查找符合条件的数据
    let curEvent;
    data.forEach(function(event,index){
      if(event.rangeYear==year&&event.rangeMonth==month&&event.rangeDay==day){
        curEvent = event;
        return;
      }
    })
    //找到返回curEvent，找不到返回false
    return curEvent?curEvent:false;
  }
  //处理日期选择事件，如果是当月，触发日期选择；如果不是当月，切换月份
  handleDatePick(index, styleName,e) {
    e=e||window.event;
    let month = this.props.viewData[this.props.month]
    switch (styleName) {
      case 'thisMonth':
        break
      case 'prevMonth':
        this.props.prevMonth() 
        break
      case 'nextMonth':        
        this.props.nextMonth()
        break
    }
    this.props.datePick(month[index])
  }

  //处理选择时选中的样式效果
  //利用闭包保存上一次选择的元素，
  //在月份切换和重新选择日期时重置上一次选择的元素的样式
  changeColor() {
    let previousEl = null
    return function (event) {
      let name = event.target.nodeName.toLocaleLowerCase()
      if (previousEl && (name === 'i' || name === 'td')) {
        previousEl.style = ''
      }
      if (event.target.className === 'thisMonth') {
        event.target.style = 'background:#F8F8F8;color:#000'
        previousEl = event.target
      }
    }
  }

  //绑定颜色改变事件
  componentDidMount() {
    let changeColor = this.changeColor()
    document.getElementById('wrapper')
      .addEventListener('click', changeColor, false);

  }
  render() {
    //确定当前月数据中每一天所属的月份，以此赋予不同className
    let month = this.props.viewData[this.props.month],
      rowsInMonth = [],
      i = 0,
      styleOfDays = (()=> {
        let i = month.indexOf(1),
          j = month.indexOf(1, i + 1),
          arr = new Array(42)
        arr.fill('prevMonth', 0, i)
        arr.fill('thisMonth', i, j)
        arr.fill('nextMonth', j)
        return arr
      })()

    //循环当前月份数据，筛选出要显示的周的数据
    let _this=this;
    console.log("i am month"+month)
    let curI=-1;
    let bOk=true;
    month.forEach((day, index)=> {
      let curArr = month.slice(index, index + 7);
      if (index % 7 === 0 ) {
        if(bOk){
          curI++;
        }
        //当这一周的数据中包含已经选中的日期时，把这周的数据push到rowsInMonth中；有时30号或者1号这些日期，month中会包含这个月和相邻月份的数据，筛选掉
        if(curArr.indexOf(_this.props.day)!=-1&&_this.props.day<=index+8&&bOk){
          rowsInMonth.push(month.slice(index, index + 7));
          bOk=false;
        }
      }
    })
    console.log("rowsInMonth:"+rowsInMonth)
    console.log("i am curI:"+curI)
    return (
      <table className="calendarMain">
        <tbody>
        {
          rowsInMonth.map((row, rowIndex)=> {
            return (
              <tr key={rowIndex}>
                {
                  row.map((day)=> {
                    let curEvent=this.handleEventSelect(this.props.year, this.props.month, day, styleOfDays[i+curI*7],Data);
                    curEvent = curEvent.eventLists;
                    return (
                      <td className={styleOfDays[i+curI*7]}
                          onClick={
                            this.handleDatePick.bind
                            (this, i+curI*7, styleOfDays[i+curI*7])}
                          key={i++}>
                        <div className={(day==this.props.day&&styleOfDays[i-1+curI*7]=="thisMonth")?"preWeekDayClicked":"preWeekDay"}>
                          <b>{day}</b>{curEvent?("--"+curEvent.length+"张卡片"):""}
                          {
                            curEvent&&curEvent.map(function(item,index){
                              {/*strLists+="<div className='addClicked' >"+item.eventDes+"</div>";
                              console.log(strLists)
                              if(index<2){*/}
                                return <div className="addClicked" >{item.eventDes}</div>
                              {/*}else if(index==2){
                                return <div className="addClicked">...</div>
                              }else{
                                return;
                              }*/}
                              
                            })
                          }
                          <div className={(day==this.props.day&&styleOfDays[i-1+curI*7]=="thisMonth")?"addClicked":"addUnClick"} onClick={this.props.showAddEvent}>添加屏幕播放内容...</div>
                        </div>
                        
                      </td>
                    )
                  })
                }
              </tr>
            )
          })
        }
        </tbody>
      </table>
    )
  }
}
//添加事件对话框组件
class AddEventDialogue extends React.Component{
  handleSubmit(){
    let year=this.props.year,
        month=this.props.month,
        day=this.props.day,
        formId=document.getElementById('newEvent');
  }
  render(){
    return(
      <div className="addForm-container fadeIn animated">
        <div className="addForm-window container row-centered">
          <div >
            <div className="box box-info ">
              <div className="box-header with-border">
                <h3 className="box-title">添加屏幕播放内容</h3>
              </div>
              <form className="form-horizontal" id="addEvent">
                <div className="box-body">
                  <div className="form-group">
                    <label for="eventDes" className="col-sm-3 control-label">任务描述</label>
                    <div className="col-sm-9">
                      <input type="text" className="form-control" id="eventDes" placeholder="任务描述"/>
                    </div>
                  </div>
                  <div className="form-group">
                    <label for="screenName" className="col-sm-3 control-label">屏幕名称</label>
                    <div className="col-sm-9">
                      <input type="text" className="form-control" id="screenName" placeholder="屏幕名称"/>
                    </div>
                  </div>
                  <div className="form-group">
                    <label for="startTime" className="col-sm-3 control-label">开始时间</label>

                    <div className="col-sm-9">
                      <input type="date" className="form-control" id="startTime" placeholder="开始时间"/>
                    </div>
                  </div>
                  <div className="form-group">
                    <label for="endTime" className="col-sm-3 control-label">结束时间</label>

                    <div className="col-sm-9">
                      <input type="date" className="form-control" id="endTime" placeholder="结束时间"/>
                    </div>
                  </div>
                  <div className="form-group">
                    <label for="repeat" className="col-sm-3 control-label">是否重复</label>
                    <div className="col-sm-3">
                      <select className="form-control">
                        <option value="不重复">不重复</option>
                        <option value="每天">每天</option>
                        <option value="每周">每周</option>
                        <option value="每天">每月</option>
                        <option value="每周">每年</option>
                      </select>
                    </div>
                  </div>
                  <div className="eventDialogueExtend">
                    <EventDialogueExtend />
                  </div>
                </div>
                <div className="box-footer">
                  <button type="button"className="btn btn-default" onClick={this.props.cancle}>取消</button>
                  <button type="submit" className="btn btn-info pull-right" onClick={this.handleSubmit.bind(this)}>提交</button>
                </div>
              </form>
            </div>
            
          </div>
        </div>
      </div>
    )
  }
}
class EventDialogueExtend extends React.Component{
  render(){
    return (
      <div><span>这是扩展组件显示内容</span></div>
    )
  }
}